package com.idp.web.shop.controller;

import com.idp.web.shop.entity.News;
import com.idp.web.shop.service.NewsService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idp.common.base.BaseController;
import com.idp.common.model.Response;
import com.idp.common.persistence.Page;
import com.idp.common.util.ValidateUtils;

/**
 * 新闻类容controller
 * 	2018-04-12 WuJiangWu
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {

	private Logger logger = Logger.getLogger(NewsController.class);

	@Resource
	private NewsService newsService;
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	初始化查询页面
	 * @return
	 */
	@RequestMapping("/init")
	public String init(){
		
		return "shop/news/newsSearch";
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	分页查询
	 * @param news
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping("/list")
	public String list(News news,Page<News> page,HttpServletRequest request){
		try {
			request.setAttribute("page", newsService.findByPage(news, page));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shop/news/newsList";
	}

	/**
	 * 	2018-04-12 WuJiangWu
	 * 	新增修改页面初始化
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/news")
	public String news(String id,HttpServletRequest request){
		try {
			if(ValidateUtils.isNotEmpty(id)){
				News news = newsService.getById(id);
				request.setAttribute("news", news);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return "shop/news/news";
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	保存
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Response save(News news){
		Response json = new Response();
		try {
			// 修改
			if(ValidateUtils.isNotEmpty(news.getId())){
				
				newsService.update(news);
			}
			// 新增
			else{
				newsService.add(news);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setErrcode(-1);
			json.setMsg("保存失败");
		}
		return json;
	}
	
	/**
	 * 	2018-04-12 WuJiangWu
	 * 	删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Response delete(String id){
		Response json = new Response();
		try {
			newsService.delete(id);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			json.setErrcode(-1);
			json.setMsg("刪除失败");
		}
		return json;
	}
}
